package com.laot.searchManage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laot.searchManage.mapper.DynamicMenusMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.laot.seacher_master.model.entity.User;
import org.laot.seacher_master.model.enums.UserRoleEnum;
import org.laot.searchManage.entry.DynamicMenus;
import org.laot.searchManage.service.IDynamicMenusService;
import org.laot.searchManage.vo.MenusInfoVo;
import org.laot.searchManage.vo.MenusVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author laoT
* @description 针对表【dynamic_menus(管理端菜单动态路由表)】的数据库操作Service实现
* @createDate 2024-02-02 17:06:38
*/
@Service
public class DynamicMenusServiceImpl extends ServiceImpl<DynamicMenusMapper, DynamicMenus>
    implements IDynamicMenusService {
    @Resource
    private DynamicMenusMapper dynamicMenusMapper;

    @Override
    public MenusInfoVo getInfo(User user) {
        //拿到用户身份
        String userRole = user.getUserRole();
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRole);
        if(userRoleEnum == null || userRoleEnum == UserRoleEnum.BAN){
            //当前用户没有权限信息,返回空值
            return null;
        }
        //根据权限查询所有的菜单
        List<MenusVo> menusVos = dynamicMenusMapper.getByRole(userRoleEnum.getNum());
        if(CollectionUtils.isEmpty(menusVos)) return null;
        //拿到父菜单为空的菜单
        List<MenusVo> menus = menusVos.stream()
                .filter(a -> a.getParentId() == null)
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(menus)) return null;
        //根据父菜单分组，过滤父菜单为空的菜单
        Map<Integer, List<MenusVo>> menusMap = menusVos.stream()
                .filter(a -> a.getParentId() != null)
                .collect(Collectors.groupingBy(MenusVo::getParentId));
        //遍历父菜单
        for (MenusVo menu : menus) {
            //封装子菜单
            addChild(menu,menusMap);
        }
        //封装返回数据
        MenusInfoVo menusInfoVo = new MenusInfoVo();
        menusInfoVo.setMenus(menus);
        List<String> ruleNames = new ArrayList<>();
        ruleNames.add(userRole);
        menusInfoVo.setRuleNames(ruleNames);
        return menusInfoVo;
    }

    private void addChild(MenusVo currentMenu, Map<Integer, List<MenusVo>> menusMap){
        //获取子菜单
        List<MenusVo> childMenus = menusMap.get(currentMenu.getId());
        if(CollectionUtils.isEmpty(childMenus)) return;
        currentMenu.setChild(childMenus);
        //遍历子菜单
        for (MenusVo childMenu : childMenus) {
            addChild(childMenu,menusMap);
        }
    }
}




